package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.GetLocationUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String businessAddress;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常(地址为空，购物车数据为空)
        //查询当前用户地址数据
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //地址为空，抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //校验用户地址与商家地址距离是否小于5公里
        //1,获取当前用户地址经纬度，先获取用户的地址，再通过API调用获取经纬度
        //获取用户的完整地址，需要拼接
        String userAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        String userCoordinate = GetLocationUtil.getCoordinate(userAddress);
        //2,获取商家经纬度
        String businessCoordinate = GetLocationUtil.getCoordinate(businessAddress);
        //3，计算距离
        double distance = GetLocationUtil.getDistance(userCoordinate, businessCoordinate);
        //4，判断是否小于5公里
        if (distance > 5000){
            throw new OrderBusinessException(MessageConstant.DISTANCE_TOO_FAR);
        }
        //查询当前用户信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        
        //查询当前用户的购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            //购物车为空，抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        // 补充设置地址和用户名
        orders.setAddress(addressBook.getDetail()); // 设置详细地址
        orders.setUserName(user.getName()); // 设置用户名
        
        orderMapper.insert(orders);
        //向订单明细表插入n条数据
        List<OrderDetail> orderDetailList =new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
//        5,封装VO对象返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        log.info("跳过微信支付，支付成功");
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //通过websocket向客户端浏览器推送消息  type,orderId,content
        Map map = new HashMap();
        map.put("type", 1);//1,表示来单提醒，2，表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:"+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }
/**
 * 根据id查询订单的详细信息
 */
    @Override
    @Transactional
    public OrderVO getOrderDetail(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        orderVO.setOrderDetailList(orderDetailMapper.listByOrderId(id));
        return orderVO;
    }
/**
 * 历史订单分页查询
 */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //用pagehelper进行分页查询
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        Long total = page.getTotal();
        List<OrderVO> orderVOList = page.getResult();
        //封装VO
        for (OrderVO orderVO : orderVOList) {
            orderVO.setOrderDetailList(orderDetailMapper.listByOrderId(orderVO.getId()));
        }
        return new PageResult(total, orderVOList);

    }

    @Override
    public void cancel(Long id) {
        orderMapper.updateStatusById(id, Orders.CANCELLED);
    }
    /**
     * 再来一单
     * */

    @Override
    @Transactional
    public void reOrder(Long id) {
        //获取订单中的菜品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(id);
        //将菜品信息加入购物车
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .userId(BaseContext.getCurrentId())
                    .image(orderDetail.getImage())
                    .amount(orderDetail.getAmount())
                    .dishId(orderDetail.getDishId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .setmealId(orderDetail.getSetmealId())
                    .number(orderDetail.getNumber())
                    .build();
                    shoppingCartMapper.insert(shoppingCart);
        }

    }

    @Override
    public PageResult pageQueryByCondition(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQueryByCondition(ordersPageQueryDTO);
        //添加一些必要信息？
        for(OrderVO orderVO:page){
            List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(orderVO.getId());
            String orderDishes = orderDetails.stream()
                    .map(detail -> detail.getName() + "*" + detail.getNumber())
                    .collect(Collectors.joining(";"));
            orderVO.setOrderDishes(orderDishes);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.updateStatusById(ordersConfirmDTO.getId(),Orders.CONFIRMED);
    }

    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.updateStatusByCancel(ordersCancelDTO, Orders.CANCELLED);
    }

    @Override
    public void rejectByAdmin(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.updateStatusByReject(ordersRejectionDTO, Orders.CANCELLED);
    }

    @Override
    public void delivery(Long id) {
        orderMapper.updateStatusById(id, Orders.DELIVERY_IN_PROGRESS);
    }

    @Override
    public OrderOverViewVO statistics() {
        OrderOverViewVO orderOverViewVO =orderMapper.statistics();
        return orderOverViewVO;
    }

    @Override
    public void complete(Long id) {
        orderMapper.updateStatusById(id, Orders.COMPLETED);
    }

    @Override
    public void reminder(Long id) {
        Orders odersDB=orderMapper.getById(id);
        if(odersDB==null ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type", 2);//1,表示来单提醒，2，表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号:"+odersDB.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }
}
